/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ddnsserver;

/**
 *
 * @author Do Viet Trung
 */
/*
 * BorderLayoutDemo.java is a 1.4 application that requires no other files.
 */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ConfigurationDomain implements ActionListener {
    private  static boolean RIGHT_TO_LEFT = false;

    private JFrame frame;
    private Container pane;
    private JPanel paneCenter,
            panePageEnd;
    private GridLayout gridCenter;
    private GridBagLayout gridBagLayout1 = new GridBagLayout();
    private GridBagConstraints gridBagCons = new GridBagConstraints();
    private JButton btnOk,
            btnCancel;

    private JLabel lblDomainName;
    private JLabel lblTTL,
            lblNameServer,
            lblEmailAddress,
            lblSerial,
            lblRefesh,
            lblReply,
            lblExpire,
            lblMinimum,
            lblNameServerOption,
            lblMiscellaneousOption;

    private JTextField txtDomainName;
    private JLabel lblServer;
    private JTextField txtServer;
    private JTextField txtTTL,
            txtNameServer,
            txtEmailAddress,
            txtSerial,
            txtRefesh,
            txtReply,
            txtExpire,
            txtMinimum;
//    private JTextField txtListenOnInterfaces;
    private JComboBox cbxAllowQuery;
    private JButton btnAdd;
    private JLabel lblHost;
    private JTextArea txtHost;
    private JScrollPane spHostScroll;

    private Domain domainConf;
//    private int index;

    private JPanel createCenterPane() {
        gridCenter = new GridLayout(0, 2);
        paneCenter = new JPanel(new BorderLayout ());
        JPanel center = new JPanel (gridCenter);
        JPanel bottom = new JPanel (new BorderLayout());

        lblDomainName = new JLabel ("   Domain: ");
        lblTTL = new JLabel("   TTL: ");
        lblNameServer = new JLabel("   Name-Server: ");
        lblEmailAddress = new JLabel("   Email Address:");
        lblSerial = new JLabel("   Serial: ");
        lblRefesh = new JLabel("   Refesh time: ");
        lblReply = new JLabel("   Reply time: ");
        lblExpire = new JLabel("   Expire time: ");
        lblMinimum = new JLabel("   Minimum time: ");
        lblNameServerOption = new JLabel("  +  Name Server Options: ");
        lblMiscellaneousOption = new JLabel("  +  Miscellaneous Options: ");


        txtDomainName = new JTextField (10);
        txtTTL = new JTextField(10);
        txtNameServer = new JTextField(10);
        txtEmailAddress = new JTextField(10);
        txtSerial = new JTextField(10);
        txtRefesh = new JTextField(10);
        txtReply = new JTextField(10);
        txtExpire = new JTextField(10);
        txtMinimum = new JTextField(10);

        String []yesNo = {"Yes", "No"};
        cbxAllowQuery = new JComboBox (yesNo);
        //txtAllowQuery = new JTextField(10);
//        txtListenOnInterfaces = new JTextField (10);
//        txtListenOnInterfaces.add(new JTextField (10));

        btnAdd = new JButton ("Add");
        btnAdd.setActionCommand("btnAdd");
        btnAdd.addActionListener(this);

        lblNameServerOption.setForeground(Color.red);
        center.add(lblNameServerOption);
        center.add(new JLabel( " "));
        
        center.add (lblDomainName);
        center.add (txtDomainName);

        center.add(lblNameServer);
        center.add(txtNameServer);
        
        center.add(lblTTL);
        center.add(txtTTL);
        
        center.add(lblEmailAddress);
        center.add(txtEmailAddress);

        center.add(lblSerial);
        center.add(txtSerial);

        center.add(lblRefesh);
        center.add(txtRefesh);

        center.add(lblReply);
        center.add(txtReply);

        center.add(lblExpire);
        center.add(txtExpire);

        center.add(lblMinimum);
        center.add(txtMinimum);

        lblMiscellaneousOption.setForeground(Color.red);
        center.add(lblMiscellaneousOption);
        center.add(new JLabel( " "));

        center.add(new JLabel("   Allow Query: "));
        center.add (cbxAllowQuery);
        //paneCenter.add(txtAllowQuery);

//        center.add(new JLabel("   Listen On Port 53 In Interfaces: "));
//        center.add(txtListenOnInterfaces);

//        paneCenter.add (btnAdd);

        lblHost = new JLabel ("Host:                                        ");
        JPanel label = new JPanel ();
        label.add (lblHost);
        label.add (new JLabel ("                                            "));
        label.add (new JLabel ("                                            "));
        bottom.add (label, BorderLayout.PAGE_START);

        txtHost = new JTextArea ();
        txtHost.setLineWrap(true);
        txtHost.setWrapStyleWord(true);
        txtHost.setFont(new Font ("Vernada", Font.PLAIN, 12));
        txtHost.setAutoscrolls(true);
//        txtHost.setPreferredSize(new Dimension (620, 100));
        spHostScroll = new JScrollPane (txtHost);
        //spHostScroll.setVerticalScrollBarPolicy(
	//	JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        spHostScroll.setPreferredSize(new Dimension(600, 150));

        bottom.add (spHostScroll, BorderLayout.CENTER);
        paneCenter.add (center, BorderLayout.CENTER);
        paneCenter.add (bottom, BorderLayout.PAGE_END);

        return paneCenter;
    }

    private JPanel createPageEnd() {
        //panePageEnd = new JPanel(gridBagLayout1);
        panePageEnd = new JPanel(new GridLayout ());
        panePageEnd.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2) );

        btnOk = new JButton("OK");
        btnOk.setActionCommand("btnOk");
        btnOk.addActionListener(this);

        btnCancel = new JButton("Cancel");
        btnCancel.setActionCommand("btnCancel");
        btnCancel.addActionListener(this);

        

        /*
        lblPad = new JLabel("         ");
        
        gridBagCons.gridx = 0;
        gridBagCons.gridy = 0;
        gridBagCons.weighty = 2;
        gridBagCons.gridheight = 2;
        gridBagCons.insets = new Insets(5,0,0,0);
        gridBagCons.gridwidth = 1;
        panePageEnd.add(btnOk, gridBagCons);

        gridBagCons.gridx = 1;
        gridBagCons.gridy = 0;
        gridBagCons.weighty = 2;
        gridBagCons.gridheight = 2;
        gridBagCons.insets = new Insets(5,0,0,0);
        panePageEnd.add(lblPad, gridBagCons);

        gridBagCons.gridx = 2;
        gridBagCons.gridy = 0;
        gridBagCons.weighty = 2;
        gridBagCons.gridheight = 2;
        gridBagCons.insets = new Insets(5,0,0,0);
        panePageEnd.add(btnCancel, gridBagCons);

         */
        panePageEnd.add(btnOk);
        panePageEnd.add(btnCancel);
        
        return panePageEnd;
    }

    public Container addComponentsToPane() {
        pane = frame.getContentPane();
        if (!(pane.getLayout() instanceof BorderLayout)) {
            pane.add(new JLabel("Container doesn't use BorderLayout!"));

            return null;
        }

        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(
                java.awt.ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.add(createCenterPane(), BorderLayout.CENTER);
        pane.add(createPageEnd(), BorderLayout.PAGE_END);

        return pane;
    }
 
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("Converter")) {
            DNSConvert DC = new DNSConvert();
            DC.createAndShowGUI();
        }

        if ("btnOk".equals(e.getActionCommand())) {
            // get all field
            this.domainConf.domainName = this.txtDomainName.getText();
            this.domainConf.nameServer.setHostName(this.txtNameServer.getText());
            this.domainConf.nameServer.setTTL(this.txtTTL.getText());
            this.domainConf.nameServer.setRoot(this.txtEmailAddress.getText());
            this.domainConf.nameServer.setExpireTime(this.txtExpire.getText());
            this.domainConf.nameServer.setSerialTime(this.txtSerial.getText());
            this.domainConf.nameServer.setRefeshTime(this.txtRefesh.getText());
            this.domainConf.nameServer.setReplyTime(this.txtReply.getText());
            this.domainConf.nameServer.setExpireTime(this.txtExpire.getText());
            this.domainConf.nameServer.setMinimumTime(this.txtMinimum.getText());
            
            int line = this.txtHost.getLineCount();
            String str = this.txtHost.getText();
            String []host = new String [line -1];
            int len = str.length();
            int oldIdx = 0;
            int i = 0;
            for (int idx = 0; idx < len; ++idx) {
                if (str.charAt(idx) == '\n') {
                    host[i] = str.substring(oldIdx, idx);
                    oldIdx = idx +1;

                    String  option[] = this.getOption(host [i]);
                    if (option [0].equals("- SOA:")) {
                        this.domainConf.Hosts.elementAt(i).setHostName(option [1]);
                    } else if (option [0].equals("- NS:")) {
                        this.domainConf.Hosts.elementAt(i).setHostName(option [1]);
                    } else if (option [0].equals("- MX (Mail Exchage):")) {
                        this.domainConf.Hosts.elementAt(i).setHostName(option [1]);
                        this.domainConf.Hosts.elementAt(i).setOther(option [2]);
                    } else if (option[1].equals("IN A")) {
                        this.domainConf.Hosts.elementAt(i).setHostName(option [0]);
                        this.domainConf.Hosts.elementAt(i).setAddress(option [2]);
                    } else if (option [1].equals("IN CNAME")) {
                        this.domainConf.Hosts.elementAt(i).setHostName(option [0]);
                        this.domainConf.Hosts.elementAt(i).setAddress(option [2]);
                    }

                    i ++;
                }
            }

            DNSConvert.setDomain(
                    DNSConvert.getTopDomain(),
                    this.domainConf.Folder,
                    domainConf);
            
            this.frame.setVisible(false);
        }

        if ("btnCancel".equals(e.getActionCommand())) {
            this.frame.setVisible(false);
        }
    }

    private String[] getOption (String str) {
        String []option = new String [3];

        int i = 0;
        int oldIdx = 0;
        for (int idx = 0; idx < str.length(); ++idx) {
            if (str.charAt(idx) == '\t') {
                option [i]  = str.substring(oldIdx, idx);

                oldIdx = idx + 1;
                i ++;
            }

            if (idx == str.length() -1) {
                option [i] = str.substring(oldIdx, str.length());

                oldIdx = idx + 1;
                i ++;
            }
        }

        return option;
    }

    public void setTextToGUI (Domain domain) {
        this.txtDomainName.setText (domain.domainName);
        this.txtNameServer.setText (domain.nameServer.getHostName());
        this.txtTTL.setText(domain.nameServer.getTTL());
        this.txtEmailAddress.setText(domain.nameServer.getRoot());
        this.txtSerial.setText(domain.nameServer.getSerial());
        this.txtRefesh.setText(domain.nameServer.getRefeshTime());
        this.txtReply.setText (domain.nameServer.getReplyTime());
        this.txtExpire.setText(domain.nameServer.getExpireTime());
        this.txtMinimum.setText(domain.nameServer.getMinimumTime());

//        this.txtListenOnInterfaces.setText(domain.fileNS.substring(
//                domain.fileNS.indexOf('[') + 1, domain.fileNS.indexOf(']')));

        int len = domain.Hosts.size();
        for (int idx = 0; idx < len; ++idx) {
            String strHost = "";

            if (domain.Hosts.elementAt(idx).getHostType().equals (
                    Host.TYPE_HOST.MX)) {
                strHost += "- MX (Mail Exchage):\t";
                strHost += domain.Hosts.elementAt(idx).getHostName();
                strHost += "\t";
                strHost += domain.Hosts.elementAt(idx).getOther();
                strHost += "\n";
            }

            if (domain.Hosts.elementAt(idx).getHostType().equals (
                    Host.TYPE_HOST.A)) {
                strHost += domain.Hosts.elementAt(idx).getHostName();
                strHost += "\tIN A\t";
                strHost += domain.Hosts.elementAt(idx).getAddress();
                strHost += "\n";
            }

            if (domain.Hosts.elementAt(idx).getHostType().equals (
                    Host.TYPE_HOST.CNAME)) {
                strHost += domain.Hosts.elementAt(idx).getHostName();
                strHost += "\tIN CNAME\t";
                strHost += domain.Hosts.elementAt(idx).getAddress();
                strHost += "\n";
            }

            
            txtHost.append(strHost);
        }

        this.domainConf = domain;
    }

    public void createAndShowGUI (Domain domain, int index) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        frame = new JFrame("Configuration DNS Domain");
//        frame.setLocation(200, 200);
        //.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.setContentPane(addComponentsToPane());

        setTextToGUI (domain);
//        this.index = index;
//        frame.setPreferredSize(new Dimension(310, 320));

        frame.pack();
        frame.setVisible(true);
        frame.setSize(480, 550);
        frame.setResizable(false);
        frame.setLocationRelativeTo(DNSConvert.frame);
    }
}